import { RouteRecordRaw } from 'vue-router'
import { staticRouters } from '@/router/basics.router'
import router from '@/router/index'

const modules = import.meta.glob('../views/**/*.vue')

// 路由过滤
const filterAsyncRoute = (routes, routerRecord: any = []): RouteRecordRaw[] => {
  routes.forEach(route => {
    const { router: path, name: title, menuTrees: children } = route
    const router: any = {
      path,
      name: path,
      meta: {
        title
      }
    }
    if (children?.length) {
      filterAsyncRoute(children, routerRecord)
    } else {
      router.component = modules[`../views${path}.vue`]
      routerRecord.push(router)
    }
  })
  return routerRecord
}

// 生成动态路由
export const generatorDynamicRouter = routes => {
  const dynamicRouters = filterAsyncRoute(routes)
  const layout: any = staticRouters.find(todo => {
    return todo.name === 'Layout'
  })
  layout.children = [...dynamicRouters, ...layout.children]
  router.addRoute(layout)
  // router.addRoute({ path: '/:pathMatch(.*)*', redirect: '/error/404' }) //不能放到静态路由里,会导致刷新页面直接匹配到404页面
}
